package org.jeecg.modules.villageCadreAssist.service.impl;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.util.SecurityUtil;
import org.jeecg.modules.villageCadreAssist.entity.VcaFileTemplate;
import org.jeecg.modules.villageCadreAssist.entity.VcaFileItem;
import org.jeecg.modules.villageCadreAssist.mapper.VcaFileItemMapper;
import org.jeecg.modules.villageCadreAssist.mapper.VcaFileTemplateMapper;
import org.jeecg.modules.villageCadreAssist.service.IVcaFileTemplateService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Collection;

/**
 * @Description: vca_file_template
 * @Author: jeecg-boot
 * @Date:   2022-02-23
 * @Version: V1.0
 */
@Service
public class VcaFileTemplateServiceImpl extends ServiceImpl<VcaFileTemplateMapper, VcaFileTemplate> implements IVcaFileTemplateService {

	@Autowired
	private VcaFileTemplateMapper vcaFileTemplateMapper;
	@Autowired
	private VcaFileItemMapper vcaFileItemMapper;

	@Override
	@Transactional
	public void saveMain(VcaFileTemplate vcaFileTemplate, List<VcaFileItem> vcaFileItemList) {
		Date now = new Date();
		vcaFileTemplate.setCreateTime(now);
		LoginUser user=(LoginUser)SecurityUtils.getSubject().getPrincipal();
		vcaFileTemplate.setCreateBy(user.getUsername());
		vcaFileTemplateMapper.insert(vcaFileTemplate);
		if(vcaFileItemList!=null && vcaFileItemList.size()>0) {
			for(VcaFileItem entity:vcaFileItemList) {
				//外键设置
				entity.setTemplateId(vcaFileTemplate.getId());
				vcaFileItemMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(VcaFileTemplate vcaFileTemplate,List<VcaFileItem> vcaFileItemList) {
		vcaFileTemplateMapper.updateById(vcaFileTemplate);

		//1.先删除子表数据
		vcaFileItemMapper.deleteByMainId(vcaFileTemplate.getId());

		//2.子表数据重新插入
		if(vcaFileItemList!=null && vcaFileItemList.size()>0) {
			for(VcaFileItem entity:vcaFileItemList) {
				//外键设置
				entity.setTemplateId(vcaFileTemplate.getId());
				vcaFileItemMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(Integer id) {
		vcaFileItemMapper.deleteByMainId(id);
		vcaFileTemplateMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(List<Integer> idList) {
		for(Integer id:idList) {
			vcaFileItemMapper.deleteByMainId(id);
			vcaFileTemplateMapper.deleteById(id);
		}
	}

}
